import md5 from 'md5';
import Qs from 'qs';
import axios from 'axios';
import {
	uploadUrl
} from '../api/index.js';

var url = '';
if (process.env.NODE_ENV === 'production') {
	url = window.location.protocol + '//' + window.location.host;
} else {
	url = '/';
}
// 上传图片(企微)
export const uploadImg = function(file) {
	var param = new FormData();
	var uid = localStorage.getItem('huankemao_user_id');
	var time = parseInt(new Date().getTime() / 1000);
	var corp_id = localStorage.getItem('huankemao_corp_id');
	param.append('file', file);
	param.append('corp_id', corp_id);
	var sign = md5(time + md5('huankemao' + uploadUrl + Qs.stringify({
		corp_id
	})));
	var obj = {
		uid,
		time,
		sign
	};
	return axios({
		url: url + uploadUrl,
		method: 'post',
		headers: {
			'Auth': JSON.stringify(obj)
		},
		data: param
	});
}


// 获取地址参数
export const getQuery = (variable) => {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
};

export const dateFormat = (date, format) => {
	date = new Date(date);
	var o = {
		'M+': date.getMonth() + 1, //month
		'd+': date.getDate(), //day
		'H+': date.getHours(), //hour
		'm+': date.getMinutes(), //minute
		's+': date.getSeconds(), //second
		'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
		'S': date.getMilliseconds() //millisecond
	};

	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));

	for (var k in o)
		if (new RegExp('(' + k + ')').test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k])
				.length));
		}
	return format;
}
